package com.societyGames.flashForms
{
import com.societyGames.system.EventObject;

import flash.display.DisplayObject;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.MouseEvent;

public class TreeViewNode extends Sprite implements IChangeSize
{
  private var _expanded:DisplayObject;
  private var _collapsed:DisplayObject;
  private var _child:DisplayObject;
  private var _horizontalContainer:HorizontalStackContainer = new HorizontalStackContainer();
  private var _treeViewContainer:TreeViewContainer = new TreeViewContainer();
  private var _sizeChangedEventObject:EventObject;
  private static const _iconIndex:int = 0;

  public function TreeViewNode(tabSize:Number, expanded:DisplayObject, collapsed:DisplayObject)
  {
    this._sizeChangedEventObject = new EventObject(this, "SIZED_CHANGED");

    this._expanded = expanded;
    this._collapsed = collapsed;

    this._horizontalContainer.buttonMode = true;
    this._horizontalContainer.addEventListener(MouseEvent.CLICK, clickHandler);
    this._horizontalContainer.sizeChangedEventObject.addEventListener(horizontalContainerSizeChangedHandler);
    this._horizontalContainer.addItem(this._treeViewContainer.isExpanded ? _expanded : _collapsed);
    this.addChild(this._horizontalContainer);

    this._treeViewContainer.x = tabSize;
    this._treeViewContainer.y = 0;
    this._treeViewContainer.sizeChangedEventObject.addEventListener(treeViewContainerSizeChangedHandler);
    this.addChild(this._treeViewContainer);
  }

  private function clickHandler(event:MouseEvent):void
  {
    this._treeViewContainer.isExpanded = !this._treeViewContainer.isExpanded;
    this._horizontalContainer.setItemAt(_iconIndex, this._treeViewContainer.isExpanded ? _expanded : _collapsed);
  }

  private function horizontalContainerSizeChangedHandler(event:Event):void
  {
    this._treeViewContainer.y = this._horizontalContainer.height;
    this._sizeChangedEventObject.dispatchEvent();
  }

  public function get child():DisplayObject
  {
    return this._child;
  }

  public function set child(value:DisplayObject):void
  {
    if (this._child != value)
    {
      if (this._child != null)
      {
        this._horizontalContainer.removeItem(this._child);
      }
      this._child = value;
      if (this._child != null)
      {
        this._horizontalContainer.addItem(this._child);
      }
    }
  }

  public function get treeViewContainer():TreeViewContainer
  {
    return this._treeViewContainer;
  }

  private function treeViewContainerSizeChangedHandler(event:Event):void
  {
    this._horizontalContainer.useHandCursor = treeViewContainer.nodeCount > 0;
    this._sizeChangedEventObject.dispatchEvent();
  }

  //IChangeSize-->
  public function get sizeChangedEventObject():EventObject
  {
    return this._sizeChangedEventObject;
  }

  //<--IChangeSize
}
}